type EventHandler = (data: any) => void;

export type WebSocketClient = WsClient;

export class WsClient {
    private ws: WebSocket | null = null;
    private eventHandlers: Map<string, EventHandler[]> = new Map();

    public connect(url: string) {
        this.ws = new WebSocket(url);
        this.ws.onopen = () => {
            console.log("Connected");
        };
        this.ws.onmessage = (event) => {
            try {
                const message = JSON.parse(event.data);
                if (message.type && this.eventHandlers.has(message.type)) {
                    this.eventHandlers.get(message.type)?.forEach(handler => 
                        handler(message.data)
                    );
                }
            } catch (error) {
                console.error('Error parsing message:', error);
            }
        };
        this.ws.onerror = this.onError.bind(this);
    }

    public on(event: string, handler: EventHandler) {
        if (!this.eventHandlers.has(event)) {
            this.eventHandlers.set(event, []);
        }
        this.eventHandlers.get(event)?.push(handler);
    }

    public send(type: string, data: any) {
        if (this.ws) {
            this.ws.send(JSON.stringify({ type, data }));
        }
    }

    public onError(e: any) {
        console.error('WebSocket error:', e);
    }

    public close() {
        this.ws?.close();
    }
}
